package com.pengtu.gsj.service.impl.task;

import java.util.Date;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.pengtu.gsj.dao.base.QueryFilter;
import com.pengtu.gsj.entity.app.Sysmenu;
import com.pengtu.gsj.entity.app.User;
import com.pengtu.gsj.entity.app.Warning;
import com.pengtu.gsj.entity.base.MailInfo;
import com.pengtu.gsj.entity.check.CheckProject;
import com.pengtu.gsj.entity.zxgc.ProjectData;
import com.pengtu.gsj.entity.zxgc.SpecialProject;
import com.pengtu.gsj.service.check.CheckModuleService;
import com.pengtu.gsj.service.check.CheckProjectService;
import com.pengtu.gsj.service.system.SysmenuManagerService;
import com.pengtu.gsj.service.system.UserService;
import com.pengtu.gsj.service.system.WarningService;
import com.pengtu.gsj.service.task.ProjectTaskService;
import com.pengtu.gsj.service.zxgc.ProjectDataService;
import com.pengtu.gsj.service.zxgc.SpecialProjectService;
import com.pengtu.gsj.utils.EmailUtils;
import com.pengtu.gsj.utils.LabelHelper;
import com.pengtu.gsj.utils.StringUtils;

@Component
@Service
@Transactional
public class ProjectTaskServiceImpl implements ProjectTaskService {
	@Autowired
	private SpecialProjectService specialProjectService;
	@Autowired
	private WarningService warningService;
	@Autowired
	private UserService userService;
	@Autowired
	private ProjectDataService projectDataService;
	@Autowired
	private SysmenuManagerService sysmenuManagerService;
	@Autowired
	private CheckProjectService checkProjectService;
	@Autowired
	private CheckModuleService checkModuleService;

	@Scheduled(cron = "0 0/59 * * * ? ")
	@Override
	public void specicalProjectTask() throws Exception {
		//获取所有未完成的专项工程
		List<SpecialProject> list  = specialProjectService.getDealProjectsByStatus();
		for (SpecialProject specialProject : list) {
			//比较当前时间和截止时间的差值是否比提前时间（h）小  如果小  就预警   大就忽略
			long hour = (specialProject.getEndTime().getTime() - System.currentTimeMillis())/(1000*60*60);
			if (hour < Long.parseLong(specialProject.getAdvanceTime())) {
				Warning existWarning = warningService.getWarningByProject(specialProject.getId());
				if (existWarning == null && hour > 0) {
					//将记录添加到数据库   判断该预警有没有存在数据库  若存在  不重复添加  当前时间过了截止时间 将该预警关闭
					Warning warning = new Warning();
					warning.setProjectId(specialProject.getId());
					warning.setStatus("0");
					warning.setNotifier("系统");
					warning.setNotifiTime(new Date());
					warning.setWarContent(specialProject.getProjectName()+"预警通知");
					//得到专项工程菜单   绑定位置信息： top left LId
					Sysmenu sysmenu = sysmenuManagerService.findSysmenuByTag("zxgc_list");
					String href = "/specialProject/listInfo.do?left="+sysmenu.getId()+"&top="+sysmenu.getParent().getId()+"&LId="+sysmenu.getId()+"&projectName="+specialProject.getProjectName();
					warning.setHref(href);
					warningService.save(warning);
					//专项工程的跳转地址
				
					//将邮件发送到各辖区局负责人的邮箱
//					String rootPath = ConfigUtils.getConfig("attachment.path");
					EmailUtils emailUtils = EmailUtils.getInstance();
					String subject = specialProject.getProjectName()+"预警";
					String content = "专项工程:"+specialProject.getProjectName()+"即将到截止时间，请在系统中处理--填报专项数据和相关文件。<br/> 专项数据："+specialProject.getDataTab();
					//附件信息
//					List<String> filePathList = new ArrayList<String>();
//					for (Attachment attachment : specialProject.getAttachments()) {
//						if (StringUtils.isEmpty(attachment.getTableId()) && "0".equals(attachment.getDelFlag())) {
//							filePathList.add(rootPath + attachment.getFullPath());
//							System.out.println("path:"+(rootPath + attachment.getFullPath()));
//						}
//					}
//					String[] fileStrings = filePathList.toArray(new String[filePathList.size()]);
					//获取素有用户信息，给其中是辖区局单位的用户发送预警信息
					//若该辖区局已经处理了专项工程数据  则不再发送   即只发送一次预警信息
					List<User> users = userService.getUsers();
					MailInfo mailInfo = null;
					for (User user : users) {
						if (user.getOrg() != null && !StringUtils.isEmpty(LabelHelper.getInstance().buildCodeName(2052, user.getOrg().getOrgNum()))) {
							//根据项目id和用户单位id  查询该单位是否已经上传了数据 
							QueryFilter queryFilter = new QueryFilter();
							queryFilter.addFilter("specialProject.id", specialProject.getId());
							queryFilter.addFilter("orgId", user.getOrg().getId());
							List<ProjectData> projectDatas = projectDataService.getProjectDatas(queryFilter);
							if (projectDatas.size() == 0) {
								mailInfo = emailUtils.getMailInfo(user.getEmail(), "", null, subject, content);
								emailUtils.sendHtmlMail(mailInfo, 3);
							}
						}
					}
				} else {
					//更新状态
					if (existWarning != null && hour < 0) {
						existWarning.setStatus("1");
						warningService.save(existWarning);
					}
				}
			}
		}
	}

	@Scheduled(cron = "0 0/5 * * * ? ")
	@Override
	public void checkResultTask() {
		//获取国检项目
		List<CheckProject> countryProjects = checkProjectService.getCheckProjectsByType("0");
		//获取省检项目
		List<CheckProject> provinceProjects = checkProjectService.getCheckProjectsByType("1");
		if (countryProjects.size() > 0) {
			checkModuleService.getTotalCheckResult(countryProjects.get(0).getId());
		} 
		if (provinceProjects.size() > 0) {
			checkModuleService.getTotalCheckResult(provinceProjects.get(0).getId());
		}
	}

	
}
